<template>
	<view>
		<view class="html2canvas" :prop="domId" :change:prop="html2canvas.create">
			<slot></slot>
		</view>
	</view>
</template>

<script>
	import { base64ToPath } from './image-tools.js';
	export default { 
		name: 'html2canvas',  
		props: {
			domId: {
				type: String,
				required: true
			}
		},
		methods: {
			async renderFinish(base64) {
				try{
					const imgPath = await base64ToPath(base64, '.png');
					this.$emit('renderFinish', imgPath);
				}catch(e){
					//TODO handle the exception
					console.log('html2canvas error', e)
				}
			},
			showLoading() {
				uni.showToast({
					title: "正在生成海报",
					icon: "none",
					mask: true,
					duration: 1000
				})
			},
			hideLoading() {
				uni.hideToast();
			} 
		}
	}
</script>

<script module="html2canvas" lang="renderjs">
import html2canvas from 'html2canvas';
import domtoimage from 'dom-to-image';

export default {
	methods: {
		async create(domId) {
			try {
				// this.$ownerInstance.callMethod('showLoading', true);
				const self = this; // 保存 this 的引用
				const timeout = setTimeout(() => {
				    const shareContent = document.querySelector(domId);
				    domtoimage.toPng(shareContent, {
				        quality: 1,
				        width: shareContent.offsetWidth * 3,
				        height: shareContent.offsetHeight * 3,
						bgcolor:'#fff',
				        style: {
				            transform: 'scale(3)',
				            transformOrigin: 'top left'
				        }
				    })
				    .then(function (dataUrl) {
				        self.$ownerInstance.callMethod('renderFinish', dataUrl);
				        self.$ownerInstance.callMethod('hideLoading', true);
				    })
				    .catch(function (error) {
						uni.hideLoading();
				        console.error('图片生成失败:', error);
				    });
				    clearTimeout(timeout);
				}, 2000);
			} catch(error){
				console.log(error)
			}
		}
	}
}
</script>


<style lang="scss">

</style>
